package com.py.custom.common.db.plugins;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;

/**
 * description：
 *
 * @author pengyou
 * @version 1.0.0
 * @date 2021/10/24
 */
@Intercepts(
        value = {
                @Signature(
                        type = StatementHandler.class,
                        method = "query",
                        args = {Statement.class, ResultHandler.class}
                ),
                @Signature(
                        type = StatementHandler.class,
                        method = "update",
                        args = {Statement.class}
                )
        }
)
@Slf4j
public class SqlPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        sql = sql.replaceAll("\n", " ");
        log.info("执行的sql：[{}]", sql);

        long startTime = System.currentTimeMillis();
        Object proceed = invocation.proceed();
        log.info("执行sql时间time：[{}] ms", (System.currentTimeMillis() - startTime));
        return proceed;
    }
}
